﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace syslog
{
    class Program
    {
        static string FilePath = "log.txt";
        static StreamWriter FileWriter = new StreamWriter(FilePath, true);


        static void Main(string[] args)
        {
            Thread U = new Thread(UDPNetMon);
            U.Start();

            Thread F = new Thread(SwapFile);
            F.Start();

            while (true)
            {
                Thread.Sleep(5000);
                FileWriter.Flush();
            }
        }

        static void UDPNetMon()
        {
            byte[] Data = new byte[1024];
            string DisData;
            IPEndPoint IP = new IPEndPoint(IPAddress.Any, 514);
            UdpClient UDPNet = new UdpClient(514);

            while (true)
            {
                
                DisData = Encoding.ASCII.GetString(UDPNet.Receive(ref IP));
                Console.WriteLine(DisData);
                FileWriter.WriteLine(DisData);
 
            }
        }

        static void SwapFile()
        {
            while (true)
            {
                Console.WriteLine("===Syslog文件计时器开始===");
                Thread.Sleep(12 * 60 * 60 * 1000);
                string DecFile = @"Data\Syslog2012-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() +"-"+DateTime.Now.Hour.ToString()+"-"+DateTime.Now.Minute.ToString()+ ".txt";
                File.Copy(FilePath, DecFile);
                FileWriter.Close();
                FileWriter = new StreamWriter(FilePath, false);                
                Console.WriteLine("===Syslog文件备份成功===");
            }
        }
    }
}
